package com.dxl.web.account.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dxl.bean.session.Session;
import com.dxl.common.consts.SysConsts;
import com.dxl.common.model.RespData;
import com.dxl.common.utils.Utils;
import com.dxl.service.account.AccountService;
import com.dxl.service.sysprop.SysPropCacheManager;
import com.dxl.web.common.controller.BaseController;
import com.dxl.web.common.utils.RequestUtils;

/**
 * 登录控制器
 * @author 邓小林
 */
@Controller
public class LoginController extends BaseController {
	@Autowired
	private AccountService accountService;
	
	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public RespData login(String account, String password, HttpServletRequest request, HttpServletResponse resp) {
		String sessionIdKey = SysPropCacheManager.getPropValue(SysConsts.LOGINED_SESSION_ID_KEY);
		String sessionId = RequestUtils.getValueFromRequest(request, sessionIdKey);
		Session session = null;
		if (Utils.isNotBlank(sessionId)) {
			session = accountService.login(sessionId, null, null);
		}
		if (Utils.isNotNull(session)) {
			return RespData.instance(RespData.SUCCESS);
		}
		
		if (Utils.isBlank(account) || Utils.isBlank(password)) {
			return RespData.instance(RespData.FAIL, "账号或者密码不能为空");
		}
		session = accountService.login(null, account, password);
		if (Utils.isNull(session)) {
			return RespData.instance(RespData.FAIL, "账号或者密码不正确");
		}
		RequestUtils.addCookie(resp, sessionIdKey, session.getId());
		return RespData.instance(RespData.SUCCESS);
	}
	
	@RequestMapping(value = "/logout")
	public void logout(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String sessionIdKey = SysPropCacheManager.getPropValue(SysConsts.LOGINED_SESSION_ID_KEY);
		String sessionId = RequestUtils.getValueFromRequest(req, sessionIdKey);
		accountService.logout(sessionId);
		RequestUtils.addCookie(resp, sessionIdKey, "", 0);
		resp.sendRedirect(RequestUtils.getRoot(req) + "/login.jsp");
	}
	
	@ResponseBody
	@RequestMapping(value = "/isLogin")
	public RespData isLogin(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String sessionIdKey = SysPropCacheManager.getPropValue(SysConsts.LOGINED_SESSION_ID_KEY);
		String sessionId = RequestUtils.getValueFromRequest(req, sessionIdKey);
		Object obj = this.cache.get(sessionId);
		return RespData.instance(RespData.SUCCESS, null, obj != null);
	}
}
